//
//  HomeTableViewController.swift
//  SinaWeibo
//
//  Created by apple on 15/11/8.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD


private let HomeCellId = "HomeCellId"
class HomeTableViewController: BaseTableViewController {
    //数据源 模型数组
    private lazy var statuses = [Status]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !userLogin{
            visitorLoginView?.setUIInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        prepareTableView()
        //获取网络数据
        loadData { (array) -> () in
            if array == nil {
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            }
            self.statuses = array!
            self.tableView.reloadData()
        }
        tableView.rowHeight = 200
    }
    
    //MARK: 注册cell
    private func prepareTableView(){
        tableView.registerClass(StatusCell.self, forCellReuseIdentifier: HomeCellId)
    }
    
    //MARK: 加载微博首页数据
    private func loadData(finished: (array: [Status]?) -> ()) {
        let AFN = AFHTTPSessionManager()
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        guard let token = UserAccountViewModel().token else{
            SVProgressHUD.showErrorWithStatus(AppErrorTip)
            return
        }
        let parameters = ["access_token": token]
        AFN.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            guard let dict = result as? [String: AnyObject] else {
                finished(array: nil)
                return
            }
            
            if let array = dict["statuses"] as? [[String: AnyObject]] {
                var list = [Status]()
                //遍历数组
                for item in array {
                    let s = Status(dict: item)
                    list.append(s)
                }

                finished(array:list)
            }
            }) { (_, error) -> Void in
                finished(array: nil)
                print(error)
        }
    }
}

extension HomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellId, forIndexPath: indexPath) as! StatusCell
        
        return cell
    }
}




